﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace ArgusPCLib
{
	/// <summary>
	/// Defines Extension-Methods for classes in the <see cref="System.Reflection"/> namespace.
	/// </summary>
	public static class SystemReflectionExtensions
	{
		public static Type[] GetParameterTypes(this MethodInfo mi)
		{
			ParameterInfo[] pis = mi.GetParameters();
			Type[] RetVal = new Type[pis.Length];
			for (int i = 0; i < pis.Length; i++)
				RetVal[i] = pis[i].ParameterType;
			return RetVal;
		}

		public static MethodInfo GetRuntimeMethod(this Type type, string methodName, Type[] parameters, bool includeNonPublic, bool includeStatic)
		{
			if (parameters == null)
				parameters = new Type[0];
			IEnumerable<MethodInfo> methods = type.GetRuntimeMethods();
			foreach (MethodInfo mi in methods)
			{
				if (!includeNonPublic && !mi.IsPublic)
					continue;
				if (!includeStatic && mi.IsStatic)
					continue;
				if (mi.Name != methodName)
					continue;

				ParameterInfo[] pis = mi.GetParameters();
				if (pis.Length != parameters.Length)
					continue;

				for (int i = 0; i < pis.Length; i++)
				{
					if (!parameters[i].Is(pis[i].ParameterType))
					{
						pis = null;
						break;
					}
				}

				if (pis != null)
					return mi;
			}
			return null;
		}
	}
}
